<?php

// +----------------------------------------------------------------------
// | 私信
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\event\pos;

use app\common\event\Base;
use app\model\pos\Pos as PosModel;
use app\model\ucenter\User as UserModel;
use app\model\pos\UserPosLevel as UserPosLevelModel;
use app\model\pos\PosLevel as PosLevelModel;
use app\model\pos\PosTransfer as PosTransferModel;
use app\model\pos\PosUser as PosUserModel;
use think\Exception;
use think\facade\Db;

class PosTransfer extends Base
{

//    /**
//     * 划转预览
//     * @param array $param
//     * @param UserModel $user
//     */
//    public function priview(UserModel $user, array $param): array
//    {
//        try {
//            if (!$user) {
//                throw new Exception('游客信息异常');
//            }
//            if ($param['type'] == 'check') {
//                // 逐个调拨
//                $pos = PosModel::where('sn', $param['sn'])->where('user_id', $user['id'])->whereNun('activate_time')->select();
//            } else {
//                $pos = PosModel::where('sn', '>=', $param['sn'])->limit($param['num'])->order('sn ASC')->where('user_id', $user['id'])->whereNun('activate_time')->select();
//            }
////            Db::startTrans();
//            $data['data']['lists'] = $pos;
//            $data['data']['num'] = count($pos);
//            $data['code'] = 0;
////            Db::commit();
//            $data['message'] = '获取成功';
//        } catch (\Exception $e) {
//            // 回滚事务
////            Db::rollback();
//            $data['code'] = 2;
//            $data['message'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
////				$data['message'] = $e->getMessage();
//        }
//        return $data;
//    }

    /**
     * 后台新增划转
     * @param $param
     * @param $admin
     * @return array
     */
//    public function gift($param, $admin)
//    {
//        try {
//            if (!$admin) {
//                throw new Exception('游客信息异常');
//            }
//            $user = UserModel::where('username', $param['username'])->find();
//            if (!$user) {
//                throw new Exception('会员信息不对');
//            }
//
//
//            $userPosLevel = UserPosLevelModel::where('user_id', $user['id'])->order('id DESC')->find();
//
//            Db::startTrans();
//            $sn = explode("\n", $param['pos_sn']);
//            $insertAll = [];
//            foreach (array_unique($sn) as $item) {
//                if (\app\model\pos\Pos::where('sn', $item)->find() > 0) {
////                    continue;
//                    throw new Exception('序列号' . $item . '已经存在');
//                }
//                $group['sn'] = $item;
//                $group['user_id'] = $user['id'];
//                $group['name'] = $param['name'];
//                $group['model'] = $param['model'];
//                $insertAll[] = $group;
//            }
//
//            // 划转记录
//            $insert = [];
//            $insert['name'] = '后台划转';
//            $insert['user_id'] = $admin['id'];
//            $insert['to_user_id'] = $user['id'];
//            $insert['pos_num'] = count($insertAll);
//            $insert['pos_sn'] = $param['pos_sn'];
//            $insert['pos_vip_id'] = $param['pos_vip_id'];
//            $transfer = PosTransferModel::create($insert);
//            if (!$transfer) {
//                throw new Exception('记录异常');
//            }
//
//            $pos = new \app\model\pos\Pos();
//            $c = $pos->saveAll($insertAll);
//
//            if (!$userPosLevel || $userPosLevel['pos_num'] < $toVip['pos_num']) {
//                // 提升等级
//                // 升级受划拨用户等级
//                $userPosLevel = [];
//                $userPosLevel['pos_num'] = $toVip['pos_num'];
//                $userPosLevel['commission'] = $toVip['commission'];
//                $userPosLevel['user_id'] = $user['id'];
//                $userPosLevel['pos_vip_id'] = $toVip['id'];
//                $userPosLevel['level'] = $toVip['level'];
//                $userPosLevel['relation_id'] = $transfer['id'];
//                $userPosLevel['type'] = 1;
//                $userPosLevel['name'] = $toVip['name'];
//                $userPosLevel['title'] = $toVip['title'];
//                UserPosLevelModel::create($userPosLevel);
//                $user['level'] = $toVip['leve'];
//                $user->save();
//            }
//
//
//            Db::commit();
//            $data['code'] = 0;
//            $data['message'] = '划转成功';
//        } catch (\Exception $e) {
//            // 回滚事务
//            Db::rollback();
//            $data['code'] = 2;
//            $data['message'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
////				$data['message'] = $e->getMessage();
//        }
//        return $data;
//    }

    /**
     * 后台新增划转
     * @param $param
     * @param $admin
     * @return array
     */
    public function adminGift($param, $admin)
    {
        try {
            if (!$admin) {
                throw new Exception('管理员信息异常');
            }
            $user = UserModel::where('id', $param['user_id'])->find();
            if (!$user) {
                throw new Exception('会员信息不对');
            }


            $count = PosModel::where('id', 'in', $param['pos_ids'])->whereNull('user_id')->where('status', 1)->count();
            $count_level = PosModel::where('id', 'in', $param['pos_ids'])->where('is_level', 1)->whereNull('user_id')->where('status', 1)->count();
            $sn = PosModel::where('id', 'in', $param['pos_ids'])->whereNull('user_id')->where('status', 1)->column('sn');

            Db::startTrans();

            if (!empty($param['level'])) {
                $pos_level = PosLevelModel::where('id', $param['level'])->find();
            } else {
                $pos_level = PosLevelModel::where('pos_num', '<=', $count_level)->order('pos_num DESC')->find();
            }

            // 划转记录
            $insert = [];
            $insert['name'] = '后台划转';
            $insert['user_id'] = $admin['id'];
            $insert['to_user_id'] = $user['id'];
            $insert['pos_num'] = $count;
            $insert['pos_sn'] = implode(',', $sn);
            $insert['pos_level_id'] = $pos_level ? $pos_level['id'] : 0;
            $transfer = PosTransferModel::create($insert);
            if (!$transfer) {
                throw new Exception('记录异常');
            }
            $update['agent_id'] = $user['agent_id'];
            $update['user_id'] = $user['id'];
            $update['buy_user_id'] = $user['id'];
            $update['transfer_time'] = time_format();
//            $userPosLevel = UserPosLevelModel::where('user_id', $user['id'])->order('id DESC')->find();
            if ($pos_level) {
                $update['pos_level_id'] = $pos_level['id'];
                if (!$user['pos_level'] || $user['pos_level'] < $pos_level['id']) {
                    // 升级受划拨用户等级
                    $userPosLevel = [];
                    $userPosLevel['pos_num'] = $pos_level['pos_num'];
                    $userPosLevel['commission'] = $pos_level['commission'];
                    $userPosLevel['user_id'] = $user['id'];
                    $userPosLevel['pos_level_id'] = $pos_level['id'];
                    $userPosLevel['level'] = $pos_level['id'];
                    $userPosLevel['relation_id'] = $transfer['id'];
                    $userPosLevel['type'] = 1;
                    $userPosLevel['name'] = $pos_level['name'];
                    $userPosLevel['title'] = $pos_level['title'];
                    $re = UserPosLevelModel::create($userPosLevel);
                    if ($re) {
                        $user['pos_level'] = $pos_level['id'];
                        $user->save();
                    } else {
                        throw new Exception('等级调整异常');
                    }
                }
            }
            $re = PosModel::where('id', 'in', $param['pos_ids'])->whereNull('user_id')->where('status', 1)->update($update);
            if (empty($re)) {
                throw new Exception('绑定pos异常');
            }


            Db::commit();
            $data['code'] = 0;
            $data['message'] = '划转成功';
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $data['code'] = 2;
            $data['message'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
//				$data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 执行划转
     * @param array $param
     * @param UserModel $user
     */
    public function transfer(array $param, UserModel $user): array
    {
        try {
            if (!$user) {
                throw new Exception('用户信息异常');
            }

            if (1 == $param['type']) {
                // 按序列号
                $lists = $user->poses()->whereNull('bind_time')->where('status', 1)->order('sn ASC')->select();
                $pos_ids = [];
                $start_sn = $param['start_sn'];
                $quantity = $param['quantity'];
                $start = false;
                foreach ($lists as $list) {
                    if ($list['sn'] == $start_sn || $start) {
                        $start = true;
                        if (count($pos_ids) < $quantity) {
                            $pos_ids[] = $list['id'];
                        }
                    }
                }
                $pos = $user->poses()->where('id', 'in', $pos_ids)->whereNull('bind_time')->where('status', 1)->select();
            } else {
                $pos = $user->poses()->where('id', 'in', $param['pos_ids'])->whereNull('bind_time')->where('status', 1)->select();
            }
            if (count($pos) == 0) {
                throw new Exception('重复提交，请返回上一级');
            }
//            if ($param['type'] == 'check') {
//                // 逐个调拨
//                $pos = PosModel::where('sn', $param['sn'])->where('user_id', $user['id'])->whereNun('activate_time')->column('id');
//                $pos_sn = PosModel::where('sn', $param['sn'])->where('user_id', $user['id'])->whereNun('activate_time')->column('sn');
//            } else {
//                $pos = PosModel::where('sn', '>=', $param['sn'])->limit($param['num'])->order('sn ASC')->where('user_id', $user['id'])->whereNun('activate_time')->column('id');
//                $pos_sn = PosModel::where('sn', '>=', $param['sn'])->limit($param['num'])->order('sn ASC')->where('user_id', $user['id'])->whereNun('activate_time')->column('sn');
//            }

            // 需要转出人保证数量
//            $uLevel = UserPosLevelModel::where('user_id', $user['id'])->order('id DESC')->find();
            $pLevel = PosLevelModel::where('id', $user['pos_level'])->order('id DESC')->find();

            if (!$pLevel) {
                throw new Exception('账号信息异常');
            }
            $all_pos = $user->poses()->where('status', 1)->count();

            if ($pLevel['id'] == 2 && 50 <= count($pos)) {
                throw new Exception('当前账号最多划转49台POS机');
            }
            if ($pLevel['id'] == 1 && 5 <= count($pos)) {
                throw new Exception('当前账号最多划转4台POS机');
            }
            // 需要保留情况
            if ($pLevel['id'] > 1 && count($pos) >= $pLevel['pos_num'] && $all_pos - count($pos) < $pLevel['pos_num']) {
                throw new Exception('当前账号需要保留' . $pLevel['pos_num'] . '台POS机');
            }
//            if ($pLevel['id'] > 1 && $all_pos - count($pos) < $pLevel['pos_num']) {
//                throw new Exception('当前账号需要保留' . $pLevel['pos_num'] . '台POS机');
//            }
//
//            // 需要保留情况
//            if ($pLevel['id'] == 2 &&  $all_pos - count($pos) < $pLevel['pos_num']) {
//                throw new Exception('当前账号需要保留' . $pLevel['pos_num'] . '台POS机');
//            }
//            if ($pLevel['id'] > 1 && $all_pos - count($pos) < $pLevel['pos_num']) {
//                throw new Exception('当前账号需要保留' . $pLevel['pos_num'] . '台POS机');
//            }

//            if ($pLevel['pos_num'] <= count($pos)) {
//                throw new Exception('当前账号最多划转' . $pLevel['pos_num'] . '台POS机');
//            }
            $uUser = UserModel::where('id', $param['transfer_user_id'])->find();

            if (!$uUser) {
                throw new Exception('账号不存在');
            }
            if ($uUser['bid'] != $user['id']) {
                throw new Exception('非直属账号无法划拨');
            }
            // 划拨提升等级
            $tLevel = PosLevelModel::where('pos_num', '<=', count($pos))->order('pos_num DESC')->find();
            if (!$tLevel) {
                throw new Exception('暂不支持划拨');
            }
            Db::startTrans();
            $insert = [];
            $insert['name'] = '上级划转';
            $insert['user_id'] = $user['id'];
            $insert['to_user_id'] = $uUser['id'];
            $insert['pos_num'] = count($pos);
            $insert['pos_sn'] = $pos->column('sn');
//            $insert['pos_vip_id'] = $tLevel['id'];
            $insert['pos_level_id'] = $tLevel['id'];
            $transfer = PosTransferModel::create($insert);
            if (!$transfer) {
                throw new Exception('记录异常');
            }
            if (isset($param['cashback_type']) && $param['cashback_type'] == 1) {
                // 返现划转
                foreach ($pos as $po) {
                    if (($po['buy_user_id'] == $user['id']) || ($po['cashback_user_id'] && $po['cashback_user_id'] == $user['id'])
                    ) {
                        // 购买者||有返现用户
                        $po['user_id'] = $uUser['id'];
//                        $po['pos_level_id'] = $tLevel['id'];
                        $po['agent_id'] = $uUser['agent_id'];
                        $po['cashback_user_id'] = $uUser['id'];
                        $po->save();
                    } else {
                        $po['agent_id'] = $uUser['agent_id'];
                        $po['user_id'] = $uUser['id'];
//                        $po['pos_level_id'] = $tLevel['id'];
                        $po->save();
                    }
                }
            } else {
                $pos->update(['user_id' => $uUser['id'], 'pos_level_id' => $tLevel['id']]);
            }

            $insertALl = [];
            foreach ($pos as $po) {
                $insertALl[] = [
                    'name' => $user['nickname'] . '划拨',
                    'type' => 0,
                    'user_id' => $uUser['id'],
                    'last_user_id' => $user['id'],
                    'relation_id' => $transfer['id'],
                    'pos_id' => $po['id'],
                    'sn' => $po['sn'],
                ];
            }
            $pUser = new PosUserModel();
            $pUser->saveAll($insertALl);

//            $toUserPosLevel =  UserPosLevelModel::where('user_id', $uUser['id'])->order('id DESC')->find();
            $toUserPosLevel = UserPosLevelModel::where('user_id', $uUser['id'])->order('id DESC')->find();
            if (!$uUser['pos_level'] || $uUser['pos_level'] < $tLevel['id']) {
                // 升级受划拨用户等级
                $userPosLevel = [];
                $userPosLevel['pos_num'] = $tLevel['pos_num'];
                $userPosLevel['user_id'] = $uUser['id'];
                $userPosLevel['level'] = $tLevel['id'];
                $userPosLevel['pos_vip_id'] = $tLevel['id'];
                $userPosLevel['pos_level_id'] = $tLevel['id'];
                $userPosLevel['relation_id'] = $transfer['id'];
                $userPosLevel['commission'] = $tLevel['commission'];
                $userPosLevel['type'] = 1;
                $userPosLevel['name'] = $tLevel['name'];
                $userPosLevel['title'] = $tLevel['title'];
                $re = UserPosLevelModel::create($userPosLevel);
                if ($re) {
                    $uUser['pos_level'] = $tLevel['id'];
                    $uUser->save();
                } else {
                    throw new Exception('等级调整异常');
                }
            }
            $data['data'] = '划拨成功';
            $data['code'] = 0;
            Db::commit();
            $data['message'] = '获取成功';
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $data['code'] = 2;
            $data['message'] = $e->getMessage();
            $data['debug'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
//				$data['message'] = $e->getMessage();
        }
        return $data;
    }


    /**
     * 执行回调
     * @param array $param
     * @param UserModel $user
     */
    public function back(array $param, UserModel $user): array
    {
        try {
            if (!$user) {
                throw new Exception('用户信息异常');
            }

            if (1 == $param['type']) {
                // 按序列号
                $lists = $user->poses()->whereNull('bind_time')->where('status', 1)->order('sn ASC')->select();
                $pos_ids = [];
                $start_sn = $param['start_sn'];
                $quantity = $param['quantity'];
                $start = false;
                foreach ($lists as $list) {
                    if ($list['sn'] == $start_sn || $start) {
                        $start = true;
                        if (count($pos_ids) < $quantity) {
                            $pos_ids[] = $list['id'];
                        }
                    }
                }
                $pos = $user->poses()->where('id', 'in', $pos_ids)->whereNull('bind_time')->where('status', 1)->select();
            } else {
                $pos = $user->poses()->where('id', 'in', $param['pos_ids'])->whereNull('bind_time')->where('status', 1)->select();
            }
            if (count($pos) == 0) {
                throw new Exception('重复提交，请返回上一级');
            }
            // 需要转出人保证数量
//            $uLevel = UserPosLevelModel::where('user_id', $user['id'])->order('id DESC')->find();
            $pLevel = PosLevelModel::where('id', $user['pos_level'])->order('id DESC')->find();

            if (!$pLevel) {
                throw new Exception('账号信息异常');
            }
            $all_pos = $user->poses()->where('status', 1)->count();

            $toLevel = PosLevelModel::where('status', 1)->order('pos_num DESC')->where('pos_num', '<=', $all_pos - count($pos))->find();

            Db::startTrans();
            // 调整等级
            if (!$toLevel || $toLevel['id'] < $user['pos_level'])
            {
                UserPosLevelModel::where('user_id', $user['id'])->where('pos_level', $user['pos_level'])->delete();
                if (!$toLevel)
                {
                    $user['pos_level'] = 1;
                }else{
                    $user['pos_level'] = $toLevel['id'];
                }
                $user->save();
            }


            foreach ($pos as $po) {
                if ($po['user_id'] == $po['buy_user_id']) {
                    // 退回仓库
                    $po['user_id'] = null;
                    $po['buy_user_id'] = null;
                    $po['pos_level_id'] = 0;
                    $po['cashback_user_id'] = null;
                    $po['agent_id'] = null;
                    $po['order_id'] = null;
                    $po['transfer_time'] = null;
                    $po->save();
                } else {
                    // 二次划转
                    $posUser = PosUserModel::where('user_id', $user['id'])->where('pos_id', $po['id'])->order('id DESC')->find();
                    if (!$posUser) {
                        throw new Exception('序列号' . $po['sn'] . '信息缺失，请联系客服处理');
                    }
                    $po['user_id'] = $posUser['last_user_id'];
                    if ($po['cashback_user_id'] == $user['id']) {
                        $po['cashback_user_id'] = $posUser['last_user_id'];
                    }
                    $posUser->delete();
                    $po->save();
                }

            }


            $data['data'] = '回调成功';
            $data['code'] = 0;
            Db::commit();
            $data['message'] = '回调成功';
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $data['code'] = 2;
            $data['message'] = $e->getMessage();
            $data['debug'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
//				$data['message'] = $e->getMessage();
        }
        return $data;
    }
//
//    /**
//     * 执行划转
//     * @param array $param
//     * @param UserModel $user
//     */
//    public function deal( array $param,UserModel $user): array
//    {
//        try {
//            if (!$user) {
//                throw new Exception('游客信息异常');
//            }
//            if ($param['type'] == 'check') {
//                // 逐个调拨
//                $pos = PosModel::where('sn', $param['sn'])->where('user_id', $user['id'])->whereNun('activate_time')->column('id');
//                $pos_sn = PosModel::where('sn', $param['sn'])->where('user_id', $user['id'])->whereNun('activate_time')->column('sn');
//            } else {
//                $pos = PosModel::where('sn', '>=', $param['sn'])->limit($param['num'])->order('sn ASC')->where('user_id', $user['id'])->whereNun('activate_time')->column('id');
//                $pos_sn = PosModel::where('sn', '>=', $param['sn'])->limit($param['num'])->order('sn ASC')->where('user_id', $user['id'])->whereNun('activate_time')->column('sn');
//            }
//
//            // 需要转出人保证数量
//            $uVip = UserPosLevelModel::where('user_id', $user['id'])->order('id DESC')->find();
//            if (!$uVip) {
//                throw new Exception('账号信息异常');
//            }
//            if (PosModel::where('user_id', $user['id'])->count() - count($pos) < $uVip['pos_num']) {
//                throw new Exception('当前账号需要保留' . $uVip['pos_num'] . '台POS机');
//            }
//            $uUser = UserModel::where('id', $param['to_user_id'])->find();
//
//            if (!$uUser) {
//                throw new Exception('账号不存在');
//            }
//            if ($uUser['bid'] != $user['id']) {
//                throw new Exception('非直属账号无法划拨');
//            }
//
//            // 划拨提升等级
//            $tVip = PosVipModel::where('pos_num', '<', count($pos))->order('pos_num DESC')->find();
//            Db::startTrans();
//            $insert = [];
//            $insert['user_id'] = $user['id'];
//            $insert['to_user_id'] = $uUser['id'];
//            $insert['pos_num'] = count($pos);
//            $insert['pos_sn'] = $pos_sn;
//            $insert['pos_vip_id'] = $tVip['id'];
//            $transfer = PosTransferModel::create($insert);
//            if (!$transfer) {
//                throw new Exception('记录异常');
//            }
//
//            PosModel::where('id', 'in', $pos)->update(['user_id' => $uUser['id']]);
//
//            $insertALl = [];
//            foreach ($pos as $po) {
//                $insertALl[] = [
//                    'name' => $user['nickname'] . '划拨',
//                    'type' => 0,
//                    'user_id' => $uUser['id'],
//                    'last_user_id' => $user['id'],
//                    'relation_id' => $transfer['id'],
//                    'pos_id' => $po['id'],
//                    'sn' => $po['sn'],
//                ];
//            }
//            $pUser = new PosUserModel();
//            $pUser->saveAll($insertALl);
//
//            $toUserVip = UserPosLevelModel::where('user_id', $uUser['id'])->order('id DESC')->find();
//            if (!$toUserVip || $toUserVip['pos_num'] < $tVip['pos_num']) {
//                // 升级受划拨用户等级
//                $userPosLevel = [];
//                $userPosLevel['pos_num'] = $tVip['pos_num'];
//                $userPosLevel['user_id'] = $uUser['id'];
//                $userPosLevel['leve'] = $tVip['leve'];
//                $userPosLevel['pos_vip_id'] = $tVip['id'];
//                $userPosLevel['relation_id'] = $transfer['id'];
//                $userPosLevel['commission'] = $tVip['commission'];
//                $userPosLevel['type'] = 1;
//                $userPosLevel['name'] = $tVip['name'];
//                $userPosLevel['title'] = $tVip['title'];
//                UserPosLevelModel::create($userPosLevel);
//                $uUser['level'] = $tVip['leve'];
//                $uUser->save();
//            }
//            $data['data'] = '划拨成功';
//            $data['code'] = 0;
//            Db::commit();
//            $data['message'] = '获取成功';
//        } catch (\Exception $e) {
//            // 回滚事务
//            Db::rollback();
//            $data['code'] = 2;
//            $data['message'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
////				$data['message'] = $e->getMessage();
//        }
//        return $data;
//    }


}
